import React,{ useState,useEffect } from 'react';
import { Row, Col, Button, Space, Table, Input,message } from 'antd';
import { connect, history } from 'umi';
import { scrollToAnchor } from '@/utils';
import Info from '../accounts/child/info';
import TableInfo from '../accounts/child/tableInfo';
import page from '../page.less';
import { GlobalState } from '@/models/global';
import AdvancedModal from '@/components/Modal/AdvancedModal';
import styles from '../styles.less';
import {getSettlementinfo,toExamine} from '@/service/fiance/index'
import {getDict} from '@/service/common/dict'

export interface FixedBarProps {
  global: GlobalState;
  dispatch: any;
  location: any;
}
function Details({
  global: { currentRoute },
  dispatch,
  location,
}: FixedBarProps) {
  const [open, setOpen] = useState(false);
  const [idea, setIdea] = useState('');
  const [type,setType] = useState('')
  const [orderIds,setOrderIds] = useState('')
  const [auditType, setAuditType] = useState<number>();
  const [info,setInfo] = useState<any>({settlementNo:'',orderNo:'',driverName:'',companyName:'',
    rentTypename:"",plateNo:'',startTime:'',finishTime:'',settlementTypename:"",settlementAmount:'',
    settlementStatus:null,logListDtoList:[{logTime:'',logRemark:'',logPersonname:''}],handlerName:'',
    handleTime:'',handleRemark:''
  })
  const [expenseDetails,setExpenseDetails] = useState(0) // 费用明细总和
  const [expenseStatus,setExpenseStatus] = useState('') // 费用明细显示文字状态
  const [deductionColumnsList,setDeductionColumnsList] = useState<any>([]) // 扣款费用数据
  const [freeColumnsList,setFreeColumnsList] = useState<any>([]) // 减免费用数据
  const [deductionColumns,setDeductionColumns] = useState<any>([]);  // 扣款费用
  const [freeColumns,setFreeColumns] = useState<any>([]);  // 收款费用
  const [processingStatus,setProcessingStatus] = useState('')
  const [delayNo,setDelayNo] = useState('')
  // const [dict, setDict] = useState({
	// 	order_finance_settlement_status: [],
	// }) // 字典值
  const [operationRecord,setOperationRecord] = useState([])
  const settlementInfo = [
    { label: '结算单号', value: info?.settlementNo },
    { label: '订单编号', value: info?.orderCarNo },
    { label: '司机名称', value: info?.driverName },
    { label: '所属公司', value: info?.companyName },
    { label: '租赁类型', value: info?.rentTypename },
    { label: '车牌号', value: info?.plateNo },
    { label: '租赁开始日', value: info?.startTime },
    { label: '租赁结束日', value: info?.finishTime },
    { label: '结算类型', value: info?.settlementTypename },
    { label: '结算金额', value: info?.settlementAmount },
  ];
  const recordColumns = [
    { title: '操作人', dataIndex: 'logPersonname' },
    { title: '操作内容', dataIndex: 'logRemark'},
    { title: '操作时间', dataIndex: 'logTime' },
  ];
  // 弹框确定
  const onModalConfirm = () => {
    const list = []
    list.push(delayNo)
    const data = {
      settlementNo:list,
      settlementStatus:auditType,
      handleRemark:idea
    }
    toExamine(data).then((res)=>{
      if(res?.success){
        setOpen(false)
        history.push('/finance/settlementAudit')
      }else{
        setOpen(false)
      }
    })
  };
  useEffect(()=>{
    setOrderIds(location?.search?.split('id=')[1])
    setType(location?.search?.split('id=')[0])
    let settlement = 1
    getSettlementinfo({id:location?.search?.split('id=')[1]}).then((res:any)=>{
      setInfo(res?.data)
      setDelayNo(res?.data?.settlementNo)
      settlement = res?.data?.settlementStatus
      getDict(
        {
          dictKeys: [
            'order_finance_settlement_status', // 处理状态
          ],
        },
        (res1: any) => {
          // setDict(res1)
          res1?.order_finance_settlement_status.forEach((res2:any)=>{
              const ids = Number(res2.dictKey)
              if( settlement === ids){
                setProcessingStatus(res2.dictValue)
              }
          })
        },
      )
      setOperationRecord(res?.data?.logListDtoList)
      const list1: any[] = []
      const list2: any[] = []
      const list5: any[] = []
      const list6: any[] = []
      let num1 = 0
      let num2 = 0
      let option1 = {}
      let option2 = {}
      // eslint-disable-next-line no-shadow
      res?.data?.orderSettlementFeeList?.forEach((res:any)=>{
          if(res.feeType ===1){
            res[res.feeItemName] = res.feeItemAmount
            option1 = {...option1,...res}
            list5.push(res)
            num1 += Number(res?.feeItemAmount)
          }else{
            res[res.feeItemName] = res.feeItemAmount
            option2 = {...option2,...res}
            list6.push(res)
            num2 += Number(res?.feeItemAmount)
          }
      })
      const obj = {
        '合计':Number(num1.toFixed(2))
      }
      const obj1 = {
        '合计':Number(num2.toFixed(2))
      }
      option1 = {...option1,...obj}
      option2 = {...option2,...obj1}
      list1.push(option1)
      list2.push(option2)
      if(num1-num2>0){
        setExpenseDetails(Number((num1-num2).toFixed(2)))
        setExpenseStatus('需要客户补缴金额/元')
      }else{
        setExpenseDetails(Number((num2-num1).toFixed(2)))
        setExpenseStatus('需要退还客户金额/元')
      }
      setDeductionColumnsList(list1)
      setFreeColumnsList(list2)
      const list3: any[] = []
      const list4:any[] = []
      list5?.forEach((res2:any)=>{
        const obj5 = {
          title: res2?.feeItemName,
          dataIndex: res2?.feeItemName,
        }
        list3.push(obj5)
      })
      const obj2 = {
          title: '合计',
          dataIndex: '合计',
      }
      list3.push(obj2)
      setDeductionColumns(list3)
      list6?.forEach((res3:any)=>{
        const obj4 = {
          title: res3?.feeItemName,
          dataIndex: res3?.feeItemName,
        }
        list4.push(obj4)
      })
      list4.push(obj2)
      setFreeColumns(list4)
    })


  },[])
  return (
    <div className={page.page}>
      <Row style={{ marginBottom: '15px' }}>
        <Space>
          <Button
            onClick={() => {
              scrollToAnchor('basic');
            }}
          >
            结算单详情
          </Button>
          <Button
            onClick={() => {
              scrollToAnchor('info');
            }}
          >
            处理信息
          </Button>
          {info?.logListDtoList?.length>0 &&
              <Button
                onClick={() => {
                  scrollToAnchor('operationRecord');
                }}
              >
                操作记录
              </Button>
          }

        </Space>
      </Row>

      <Info
        title="结算单详情"
        info={settlementInfo}
        span={8}
        state={{ label: '处理状态', value: processingStatus }}
      />
      {info?.orderSettlementFeeList?.length>0 &&
           <TableInfo
            state={{ label: expenseStatus, value: expenseDetails }}
            columns={deductionColumns}
            title="费用明细"
            tableTitle="扣款费用项"
            pagination={false}
            dataSource={deductionColumnsList}
          >
            <Table
              columns={freeColumns}
              pagination={false}
              dataSource={freeColumnsList}
            />
          </TableInfo>
      }


      {/* 如果没有处理信息，则不显示 */}
      {info?.handlerName &&
          <div className={`${page.page} ${page.card}`} id="info">
           <div className={page.dotTitle}>处理信息</div>
           <Row gutter={24} className={page.rows}>
             <Col span={8} className={page.col}>
               <div className={page.label}>处理人员：</div>
               <div className={page.value}>{info?.handlerName}</div>
             </Col>
             <Col span={8} className={page.col}>
               <div className={page.label}>处理时间：</div>
               <div className={page.value}>{info?.handleTime}</div>
             </Col>
             <Col span={24} className={page.col}>
               <div className={page.label}>处理状态：</div>
               <div className={page.value}>{processingStatus}</div>
             </Col>
             <Col span={24} className={page.col}>
               <div className={page.label}>处理意见：</div>
               <div className={page.value}>{info?.handleRemark}</div>
             </Col>
           </Row>
         </div>
      }
     
      {/* 如果没有操作记录，则不显示 */}
      {info?.logListDtoList?.length>0 &&
        <TableInfo
          id="operationRecord"
          title="操作记录"
          columns={recordColumns}
          dataSource={operationRecord}
        />
      }

      <Row justify="center" style={{ marginTop: '20px' }}>
        {/* 不同状态显示不同的按钮 */}
        <Space>
          <Button
            shape="round"
            onClick={(e) => {
              e.stopPropagation();
              dispatch({
                type: 'global/deleteTabs',
                payload: currentRoute,
              });
              history.goBack();
            }}
          >
            关闭
          </Button>
          {type==='?type?' &&
            <>
              <Button
                shape="round"
                style={{ border: '1px solid #FDC12E', color: '#FDC12E' }}
                onClick={() => {
                  setAuditType(0);
                  setOpen(true);
                }}
              >
                拒绝结算
              </Button>
              <Button
                shape="round"
                type="primary"
                onClick={() => {
                  setAuditType(1);
                  setOpen(true);
                }}
              >
                同意结算
              </Button>
            </>
          }

        </Space>
      </Row>
      <AdvancedModal
        isOpen={open}
        title="结算款审核"
        setIsOpen={setOpen}
        footer={null}
      >
        <Row>
          <Col span={24} className={`${styles.flex} ${styles.row}`}>
            {auditType === 0 && '拒绝结算'}
            {auditType === 1 && '同意结算'}
          </Col>
          <Col span={24} className={`${styles.flex} ${styles.row}`}>
            处理意见：
            <Input.TextArea
              allowClear
              showCount
              maxLength={200}
              placeholder="请输入处理意见，不超过200个字符"
              onChange={({ target: { value } }) => {
                setIdea(value);
              }}
              defaultValue={idea}
            />
          </Col>
        </Row>
        <Row justify="center">
          <Space>
            <Button onClick={() => setOpen(false)}>关闭</Button>
            <Button type="primary" onClick={onModalConfirm}>
              确定
            </Button>
          </Space>
        </Row>
      </AdvancedModal>
    </div>
  );
}
export default connect(({ global }: any) => ({ global }))(Details);
